#!/bin/bash

source ./scripts/configs.sh

# Make symbolic links to the dotfiles
# mdkir if link item's parent path not exists
echo -e "\n## Checking source paths\n"
for item in "${link_items[@]}"; do
    # Get the parent path
    source_path=$(dirname $(dirname $0))/$item
    if [ ! -f "$source_path" ] && [ ! -d "$source_path" ]; then
        echo "source_path not exists: $source_path"
        exit 1
    fi
done

echo -e "\n## Backing up target paths\n"
for item in "${link_items[@]}"; do
    target_path=$HOME/$item
    if [ -f "$target_path" ] || [ -d "$target_path" ]; then
        echo "backup: $target_path -> $target_path.bak"
        mv "$target_path" "$target_path.bak"
    fi
done

echo -e "\n## Making dir for target path\n"
for item in "${link_items[@]}"; do
    parent_path=$HOME/$(dirname "$item")
    # Create the parent path if it doesn't exist
    if [ ! -d "$parent_path" ]; then
        # echo "parent_path not exists: $parent_path"
        echo "mkdir: $parent_path"
        mkdir -p "$parent_path"
    fi
done

echo -e "\n## Symlinking\n"
for item in "${link_items[@]}"; do
    source_path=$(realpath "$(dirname $(dirname $0))/$item")
    target_path=$HOME/$item
    echo "symlink: $source_path -> $target_path"
    # fix blank in path issue
    ln -s "$source_path" "$target_path"
done

echo -e "\n## Done\n"